﻿using System.Collections.Generic;
using System.Data;
using Model;
using Utils;
namespace Dao
{
    public class MySqlDaoBase : IDaoBase
    {
        public List<ColumnModel> GetColumnList()
        {
            // MysqlHelper.ConnectionString = "";
            DataTable dt = MysqlHelper.ExecuteDataTable("select * from Columns where table_name='" + TableName + "'");
            var lst = new List<ColumnModel>();
            DatatypeConfig dtConfig = new DatatypeConfig();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                ColumnModel column = new ColumnModel();
                string comment = dr["COLUMN_COMMENT"].ToString();
                string name = dr["COLUMN_NAME"].ToString();
                string type = dtConfig.GetDataType(dr["DATA_TYPE"].ToString());
                column.ColumnMemo = comment == "" ? name : comment;
                column.ColumnName = name;
                int maxLen = 0;
                int.TryParse(dr["CHARACTER_MAXIMUM_LENGTH"].ToString(), out maxLen);
                column.ColumnMaxLen = maxLen;
                column.ColumnType = type;
                column.IsPrimary = dr["COLUMN_KEY"].ToString() != "";
                column.ColumnNameAlias = StringUtils.GetAlias(name);
                lst.Add(column);
            }
            return lst;
        }
        /// <summary>
        /// 返回表信息
        /// </summary>
        /// <returns></returns>
        public List<TableModel> GetTable()
        {
            string sql = string.Format("select * from tables where TABLE_SCHEMA='{0}'",MySqlEntity.DataBase);
            if (!string.IsNullOrEmpty(TableName))
            {
                sql += string.Format(" and TABLE_NAME='{0}'", TableName);
            }
            DataTable dt = MysqlHelper.ExecuteDataTable(sql);
            List<TableModel> lst = new List<TableModel>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                TableModel table = new TableModel();
                table.TableName = dr["TABLE_NAME"].ToString();
                table.TableMemo = dr["TABLE_COMMENT"].ToString() == "" ? TableName : dr["TABLE_COMMENT"].ToString();
                table.TableNameAlias = StringUtils.GetAlias(table.TableName);
                lst.Add(table);
            }
            return lst;
        }

        public string TableName { get; set; }
        public string PrimaryKey { get; set; }
        /// <summary>
        /// 数据库列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetDbList()
        {
         DataTable  dt= MysqlHelper.ExecuteDataTable("show databases;");
            var lst = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                lst.Add(dr["database"].ToString());
            }
            return lst;
        }
    }
}
